package initialize

import (
	"awesomeProject/goods-web/global"
	"awesomeProject/goods-web/proto"
	"awesomeProject/goods-web/utils/otgrpc"
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver"
	"github.com/opentracing/opentracing-go"
	"go.uber.org/zap"
	"google.golang.org/grpc"
)

// InitSrvConn 通过Consul来获取后端子服务的客户端
func InitSrvConn() {

	ConsulInfo := global.ServerConfig.ConsulInfo

	// 维护负载均衡器
	consulParam := fmt.Sprintf("consul://%s:%d/%s?wait=%s&tag=%s",
		ConsulInfo.Host, ConsulInfo.Port, global.ServerConfig.GoodsSrvInfo.Name, "14s", "goods")

	// 实现负载均衡  --- 取出一个链接
	connGoods, err := grpc.Dial(consulParam, grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
		grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer()))) // 实现RR轮转负载均衡，并添加拦截器

	if err != nil {
		zap.S().Fatal("通过Consul负载均衡获得连接失败：", zap.Error(err))
		return
	}
	global.GoodsSrvClient = proto.NewGoodsClient(connGoods)

}
